package com.jdzy.student.interceptor;

import com.jdzy.common.exception.JwtCheckException;
import com.jdzy.student.properties.JwtProperties;
import com.jdzy.utils.common.JwtUtils;
import io.jsonwebtoken.JwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class StudentCheckInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
        //1、获取请求头中的令牌
        String jwt="";
        String authHeader = req.getHeader("Authorization"); // 获取完整的 "Bearer <token>" 字符串
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            jwt = authHeader.substring(7); // 去掉 "Bearer " 部分，只保留 JWT 令牌
            // 现在jwt变量中就是真正的JWT令牌了，可以进行后续验证或其他操作
        }
        //2、获取请求路径
        String url=req.getRequestURL().toString();
        log.info("请求的url:{}",url);
        //若是login(登录)操作  则放行
        if(url.contains("student/studentLogin")){
            log.info("登录操作，放行");
            return true;
        }
        //3、进行解析jwt
        try {
            JwtUtils.parseJWT(jwtProperties.getStudentSecretKey(),jwt);
        }catch (Exception exception){
            log.error("令牌解析失败");
            throw new JwtCheckException();
        }
        log.info("令牌合法,放行");
        return true;
    }

}
